<template>
  <a-modal
    :visible="visible"
    :title="t('common.assignPermission')"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirmLoading="loading"
    width="600px"
  >
    <a-spin :spinning="loading">
      <a-tree
        v-model:checkedKeys="checkedKeys"
        v-model:halfCheckedKeys="halfCheckedKeys"
        :tree-data="permissionTree"
        :field-names="{
          title: 'permissionName',
          key: 'id',
          children: 'children'
        }"
        checkable
        :defaultExpandAll="true"
      />
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import type { PermissionTreeNode } from '@/types/permission.type'
import { getPermissionTree } from '@/api/permission'
import { assignPermissions } from '@/api/permission'
import { getRolePermissions } from '@/api/role'

const { t } = useI18n()

const props = defineProps<{
  visible: boolean
  roleId: number
  defaultCheckedKeys?: number[]
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}>()

const loading = ref(false)
const permissionTree = ref<PermissionTreeNode[]>([])
const checkedKeys = ref<number[]>([])
const halfCheckedKeys = ref<number[]>([])

// 监听visible变化，当弹窗打开时获取权限树和角色权限
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchPermissionTree()
    fetchRolePermissions()
  }
})

// 监听defaultCheckedKeys变化
watch(() => props.defaultCheckedKeys, (newVal) => {
  if (newVal) {
    checkedKeys.value = newVal
  }
})

// 获取权限树
const fetchPermissionTree = async () => {
  try {
    loading.value = true
    const data = await getPermissionTree()
    permissionTree.value = data
  } catch (error: any) {
    console.error('获取权限树错误:', error)
    message.error(error.message || '获取权限树失败')
  } finally {
    loading.value = false
  }
}

// 获取角色权限
const fetchRolePermissions = async () => {
  try {
    const data = await getRolePermissions(props.roleId)
    checkedKeys.value = data
  } catch (error: any) {
    console.error('获取角色权限错误:', error)
    message.error(error.message || '获取角色权限失败')
  }
}

// 获取所有父节点ID
const getAllParentIds = (tree: PermissionTreeNode[], targetIds: number[]): number[] => {
  const parentIds = new Set<number>()
  
  const findParents = (nodes: PermissionTreeNode[], targetId: number) => {
    for (const node of nodes) {
      if (node.children) {
        if (node.children.some(child => child.id === targetId)) {
          parentIds.add(node.id)
          findParents(tree, node.id)
        }
        findParents(node.children, targetId)
      }
    }
  }

  for (const id of targetIds) {
    findParents(tree, id)
  }

  return Array.from(parentIds)
}

// 提交
const handleSubmit = async () => {
  try {
    loading.value = true
    // 获取所有选中的节点ID（包括半选状态的父节点）
    const selectedIds = [...checkedKeys.value]
    const parentIds = getAllParentIds(permissionTree.value, selectedIds)
    
    // 合并所有需要提交的权限ID
    const allPermissionIds = [...new Set([...selectedIds, ...parentIds])]
    
    console.log('提交的权限ID:', {
      selectedIds,
      parentIds,
      allPermissionIds
    })

    await assignPermissions({
      roleId: props.roleId,
      permissionIds: allPermissionIds
    })
    message.success('分配权限成功')
    emit('success')
    handleCancel()
  } catch (error: any) {
    message.error(error.message || '分配权限失败')
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}
</script> 